/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Cliente;

import Servidor.Produto;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 * * @author Leonardo
 */
public class Main extends javax.swing.JFrame {
    private TableModelProduto tabela;
    Cliente cliente = new Cliente();
    private Produto p;
    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        tabela = new TableModelProduto();
        tableProdutos.setModel(tabela);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnconecta = new javax.swing.JButton();
        campoPorta = new javax.swing.JTextField();
        campoIp = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableProdutos = new javax.swing.JTable();
        select = new javax.swing.JButton();
        updateTabela = new javax.swing.JButton();
        remove = new javax.swing.JButton();
        insert = new javax.swing.JButton();
        jTextProduto = new javax.swing.JTextField();
        jProduto = new javax.swing.JLabel();
        jMarca = new javax.swing.JLabel();
        jTextMarca = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextTipo = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextPreco = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextQuantidade = new javax.swing.JTextField();
        jAlterar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBounds(new java.awt.Rectangle(350, 200, 550, 350));

        btnconecta.setText("Conecta");
        btnconecta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnconectaActionPerformed(evt);
            }
        });

        campoPorta.setText("4242");

        campoIp.setText("127.0.0.1");

        jLabel1.setText("Porta:");

        jLabel2.setText("IP:");

        tableProdutos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableProdutos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableProdutosMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tableProdutos);

        select.setText("Buscar");
        select.setActionCommand("Listar");
        select.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectActionPerformed(evt);
            }
        });

        updateTabela.setText("Update");
        updateTabela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateTabelaActionPerformed(evt);
            }
        });

        remove.setText("Remove");
        remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeActionPerformed(evt);
            }
        });

        insert.setText("Inserir");
        insert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertActionPerformed(evt);
            }
        });

        jProduto.setText("Produto:");

        jMarca.setText("Marca:");

        jLabel4.setText("Tipo:");

        jLabel5.setText("Preço:");

        jLabel6.setText("Quantidade:");

        jAlterar.setText("Alterar");
        jAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAlterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(btnconecta, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(campoPorta, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(23, 23, 23)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(campoIp, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jProduto)
                            .addComponent(jMarca)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextProduto, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                            .addComponent(jTextMarca)
                            .addComponent(jTextTipo)
                            .addComponent(jTextPreco, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(select)
                        .addGap(18, 18, 18)
                        .addComponent(updateTabela)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(remove)
                                .addGap(18, 18, 18)
                                .addComponent(insert)
                                .addGap(18, 18, 18)
                                .addComponent(jAlterar)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextQuantidade)
                                .addGap(83, 83, 83)))))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextProduto))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jMarca)
                    .addComponent(jTextMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextPreco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6)
                        .addComponent(jLabel5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(select)
                    .addComponent(updateTabela)
                    .addComponent(remove)
                    .addComponent(insert)
                    .addComponent(jAlterar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(btnconecta, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(55, 55, 55))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnconectaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnconectaActionPerformed
        cliente.conectaServidor(campoIp.getText(),Integer.parseInt(campoPorta.getText()));
        btnconecta.disable();
    }//GEN-LAST:event_btnconectaActionPerformed

    private void selectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectActionPerformed
        cliente.enviaMsg("SELECT * FROM produtos;",0);
    }//GEN-LAST:event_selectActionPerformed

    public void limpaTabela(){
        while (tabela.getRowCount()>0)
            tabela.remove(tabela.getRowCount()-1);
    }
    
    private void updateTabelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateTabelaActionPerformed
        limpaTabela();
        ArrayList<Produto> p;
        p = cliente.getRespostaSelect();
        if(p!=null){
            for(int i=0;i<p.size();i++){
               tabela.add(p.get(i));
               System.out.println(p.get(i));
            }
        }
    }//GEN-LAST:event_updateTabelaActionPerformed

    private void tableProdutosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableProdutosMouseClicked
        int index = tableProdutos.getSelectedRow();
        if (index == -1)
            return;
        p = tabela.select(index);
        jTextProduto.setText(p.getNome());
        jTextMarca.setText(p.getMarca());
        jTextTipo.setText(p.getTipo());
        jTextPreco.setText(p.getPreco().toString());
        jTextQuantidade.setText(Integer.toString(p.getQuantidade()));
    }//GEN-LAST:event_tableProdutosMouseClicked

    private void removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeActionPerformed
        cliente.enviaMsg("DELETE FROM produtos WHERE id="+p.getID()+";",1);
    }//GEN-LAST:event_removeActionPerformed

    private void jAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAlterarActionPerformed
        cliente.enviaMsg("UPDATE produtos SET nome = '"+jTextProduto.getText()+"', marca = '"+ jTextMarca.getText()+
                "', tipo = '"+jTextTipo.getText()+"', preco = "+jTextPreco.getText()+", quantidade = "+jTextQuantidade.getText()+" WHERE id="+p.getID()+";",2);
    }//GEN-LAST:event_jAlterarActionPerformed

    private void insertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertActionPerformed
         cliente.enviaMsg("INSERT INTO produtos (nome, marca, tipo, preco, quantidade) VALUES('"+jTextProduto.getText()+"', '"+jTextMarca.getText()+
                 "', '"+jTextTipo.getText()+"',"+jTextPreco.getText()+","+jTextQuantidade.getText()+");",3);
    }//GEN-LAST:event_insertActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnconecta;
    private javax.swing.JTextField campoIp;
    private javax.swing.JTextField campoPorta;
    private javax.swing.JButton insert;
    private javax.swing.JButton jAlterar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jMarca;
    private javax.swing.JLabel jProduto;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextMarca;
    private javax.swing.JTextField jTextPreco;
    private javax.swing.JTextField jTextProduto;
    private javax.swing.JTextField jTextQuantidade;
    private javax.swing.JTextField jTextTipo;
    private javax.swing.JButton remove;
    private javax.swing.JButton select;
    private javax.swing.JTable tableProdutos;
    private javax.swing.JButton updateTabela;
    // End of variables declaration//GEN-END:variables
}
